// pages/login/login.js
const App = getApp();
const Api = require('../../utils/api.js')
// 工具类
const util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 授权登录
   */
  authorLogin: function (e) {
    let _this = this;
    console.log(e)
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      return false;
    }
    wx.showLoading({
      title: "正在登录",
      mask: true
    });
    // 执行微信登录
    wx.login({
      success: function (ret) {
        console.log(ret);
        //wx.setStorageSync('wx_code', ret.code);
        wx.getUserInfo({
          lang: "zh_CN",
          success: (res) => {
            console.log(res);
            Api.auth(res.encryptedData, res.iv, ret.code)
              .then(result => {
                console.log(result.data);
                wx.hideLoading()
                App.globalData.userInfo = result.data.data.userInfo;
                wx.setStorageSync("userInfo", result.data.data.userInfo);
                wx.setStorageSync("token", result.data.data.token);
                wx.setStorageSync("signature", result.data.data.signature);
                wx.setStorageSync("usertype", result.data.data.userInfo.usertype);
                // 0:茶企业 1:茶弄 2:茶工 3:未确定
                  wx.navigateBack({
                      delta: 1,
                      success: function (e) { console.log("成功",e) },
                      fail: function (e) { console.log("失败",e) },
                  });
              })
          }
        })
      }
    });
  },
  cancel_get: function () {
    wx.switchTab({
      url: '/pages/staff/staff',
    })
  },

  /**
   * 授权成功 跳转回原页面
   */
  navigateBack: function () {
    wx.navigateBack();
    // let currentPage = wx.getStorageSync('currentPage');
    // wx.redirectTo({
    //   url: '/' + currentPage.route + '?' + util.urlEncode(currentPage.options)
    // });
  },

})